package server

import (
	"5-28zk/common/models/mysql"
	"5-28zk/common/pkg"
	"5-28zk/common/proto/doctor"
	"errors"
	"fmt"
	"gorm.io/gorm"
)

func Login(req *doctor.LoginReq) (*doctor.LoginResp, error) {
	user, err := mysql.GetUser(req.Phone)
	if err != nil {
		return nil, errors.New("查询失败")
	}
	if user.Phone == "" {
		m := mysql.User{
			Model:    gorm.Model{},
			Phone:    req.Phone,
			Password: req.Password,
			Name:     req.Name,
		}
		err := mysql.CreateUser(&m)
		if err != nil {
			return nil, errors.New("注册失败")
		}
	}
	if user.Password != user.Password {
		return nil, errors.New("密码错误")
	}
	claims := pkg.CustomClaims{ID: user.ID}
	token, err := pkg.NewJWT("2210a").CreateToken(claims)
	if err != nil {
		return nil, errors.New("token生成失败")
	}
	return &doctor.LoginResp{Success: token}, nil
}

func PatientList(req *doctor.PatientListReq) (*doctor.PatientListResp, error) {
	list, err := mysql.GetPatientList(req.DoctorId, int(req.Status))
	if err != nil {
		return nil, errors.New("查询失败")
	}
	fmt.Println(list)
	var lists []*doctor.List
	for _, patient := range list {
		lists = append(lists, &doctor.List{
			DoctorId:       int64(patient.DoctorId),
			BedNumber:      patient.BedNumber,
			PatientName:    patient.PatientName,
			PatientAge:     int64(patient.PatientAge),
			PatientGender:  int64(patient.PatientGender),
			Diagnosis:      patient.Diagnosis,
			ChronicDisease: patient.ChronicDisease,
			AllerGen:       patient.AllerGen,
			Status:         int64(patient.Status),
		})
	}
	return &doctor.PatientListResp{List: lists}, nil
}

func PatientShow(req *doctor.PatientShowReq) (*doctor.PatientShowResp, error) {
	show, err := mysql.GetPatientShow(req.Id)
	if err != nil {
		return nil, errors.New("查询失败")
	}
	return &doctor.PatientShowResp{
		DoctorId:       int64(show.DoctorId),
		BedNumber:      show.BedNumber,
		PatientName:    show.PatientName,
		PatientAge:     int64(show.PatientAge),
		PatientGender:  int64(show.PatientGender),
		Diagnosis:      show.Diagnosis,
		ChronicDisease: show.ChronicDisease,
		AllerGen:       show.AllerGen,
		Status:         int64(show.Status),
	}, nil
}
